package com.jqsoft.launcher.activity.gairui;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.garea.device.plugin.DevicePluginCategory;
import com.garea.device.plugin.DevicePluginManager;
import com.garea.device.plugin.IDevicePlugin;
import com.garea.device.plugin.idcard.IDCardInspector;
import com.garea.device.plugin.idcard.IIDCardDevice;
import com.garea.device.plugin.idcard.IIDCardPersonInfo;
import com.garea.device.plugin.idcard.OnIDCardListener;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.PersonnelInformation;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.common.BphsConstants;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.util.BytesTransUtil;
import com.jqsoft.launcher.util.DateTools;
import com.jqsoft.launcher.util.FileService;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.StringTools;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class YiliaoServiceActivity extends JQActivity implements
        View.OnClickListener {
    private final String tag = "YiliaoServiceActivity";

    private Button chaxuan_btn, celiang_xueya_btn, celiang_xueyang_btn,
            celiang_xuetang_btn, celiang_xindian_btn, celiang_niaochanggui_btn, baocun_btn, quxiao_btn,jiaoyanbtn_btn;
    private EditText name_et, shengfenzheng_et;
    private String name_str, shengfenzheng_str;

    private TextView shousuoya_et, shuzhangya_et, xueyang_et, mailv_et,
            xuetang_et, niaocg_et, Readingtext;

    private String sPersonName, sCardNo, xueyagao, xueyadi, xueyang, mailv, kongfuxueytang, niaochanggui;
    private String content;
    private int jiciNum = 0;
    private List<PersonnelInformation> infoList = new ArrayList<PersonnelInformation>();
    @Override
    protected int getContentLayout() {
        return R.layout.yiliao_service_layout;
    }

    private IDCardInspector mInspector;
    private IIDCardDevice mDevice;
    private String sexName, birthday;

    @Override
    protected void initGui() {
        //	chaxuan_btn = (Button) findViewById(R.id.chaxuan_btn);
        //	chaxuan_btn.setOnClickListener(YiliaoServiceActivity.this);

        Readingtext = (TextView) findViewById(R.id.Readingtext);
        celiang_xueya_btn = (Button) findViewById(R.id.celiang_xueya_btn);
        celiang_xueya_btn.setOnClickListener(YiliaoServiceActivity.this);
        jiaoyanbtn_btn = (Button)findViewById(R.id.jiaoyanbtn);
        jiaoyanbtn_btn.setOnClickListener(YiliaoServiceActivity.this);
        celiang_xueyang_btn = (Button) findViewById(R.id.celiang_xueyang_btn);
        celiang_xueyang_btn.setOnClickListener(YiliaoServiceActivity.this);
        celiang_xuetang_btn = (Button) findViewById(R.id.celiang_xuetang_btn);
        celiang_xuetang_btn.setOnClickListener(YiliaoServiceActivity.this);
        celiang_xindian_btn = (Button) findViewById(R.id.celiang_xindian_btn);
        celiang_xindian_btn.setOnClickListener(YiliaoServiceActivity.this);
        celiang_niaochanggui_btn = (Button) findViewById(R.id.celiang_niaochanggui_btn);
        celiang_niaochanggui_btn.setOnClickListener(YiliaoServiceActivity.this);
        name_et = (EditText) findViewById(R.id.name_et);
        shengfenzheng_et = (EditText) findViewById(R.id.shengfenzheng_et);

        shousuoya_et = (TextView) findViewById(R.id.shousuoya_et);
        shuzhangya_et = (TextView) findViewById(R.id.shuzhangya_et);
        xueyang_et = (TextView) findViewById(R.id.xueyang_et);
        mailv_et = (TextView) findViewById(R.id.mailv_et);
        xuetang_et = (TextView) findViewById(R.id.xuetang_et);
        niaocg_et = (TextView) findViewById(R.id.niaocg_et);


        baocun_btn = (Button) findViewById(R.id.baocun_btn);
        baocun_btn.setOnClickListener(YiliaoServiceActivity.this);
        quxiao_btn = (Button) findViewById(R.id.quxiao_btn);
        quxiao_btn.setOnClickListener(leftlistener);
        mInspector = DevicePluginManager.getDeviceInspector(DevicePluginCategory.DEV_PLUGIN_CATEGORY_IDCARD_2,
                this);

        mInspector.setOnIDCardDevicePluginListener(new IDCardInspector.OnIDCardDevicePluginListener() {

            @Override
            public void onDiscoverDevice(IIDCardDevice dev) {
                Toast.makeText(YiliaoServiceActivity.this,
                        "已连接", Toast.LENGTH_SHORT).show();
                mDevice = dev;
                //自动连接
                dev.setOnDevicePluginStateListener(new DevStateListener());
                dev.setOnIDCardListener(mCardListener);
                dev.init();
            }

            @Override
            public void onMonitorDevice(IIDCardDevice dev) {
                //USB不用本函数
            }

            @Override
            public void onRemovedDevice(IIDCardDevice dev) {
                if (mDevice != null) {
                    mDevice.close();
                    mDevice.uninit();
                    mDevice = null;
                }
            }
        });
        mInspector.init();
        mInspector.searchDevice();
    }

    private class DevStateListener implements IDevicePlugin.OnDevicePluginStateListener {


        public DevStateListener() {

        }

        @Override
        public void onDeviceOpened() {

        }

        @Override
        public void onDeviceInited() {
            mDevice.open();
        }

        @Override
        public void onDeviceUninited() {
            //
        }

        @Override
        public void onDeviceClosed() {
            //
        }

        @Override
        public void onStateChanged(int arg0, int arg1) {
            //
        }
    }

    private OnIDCardListener mCardListener = new OnIDCardListener() {

        @Override
        public void onReceived(IIDCardPersonInfo d) {
            shengfenzheng_et.setText(d.getID().trim());
            name_et.setText(d.getName().trim());
            sexName = d.getSexText();
            birthday = d.getBirthday();
            infoList.clear();
            getPersonInfo();
        }

        @Override
        public void onReadFailed() {
            Toast.makeText(YiliaoServiceActivity.this, "读卡失败", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void initAction() {
        setGoBack();
    }

    @Override
    protected void initData() {
        setTitle("医疗服务");
//		if (BphsConstants.sAndroidReader) {
//			name_et.setEnabled(false);
//			shengfenzheng_et.setEnabled(false);
//			name_et.setBackgroundDrawable(getResources().getDrawable(
//					drawable.shape_grayall_corner));
//			shengfenzheng_et.setBackgroundDrawable(getResources().getDrawable(
//					drawable.shape_grayall_corner));
//		}

    }

    private Handler myhandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.TIJIAO_OVER:
                    dismissrogressBar();
                    MessageTools.showDialogOk(ctx,
                            "上传数据成功！");
                    break;
                case Constant.TIJIAO_ERROR:
                    MessageTools.showDialogOk(ctx,
                            "上传数据失败");
                    break;
                case Constant.BAOCUN_OVER:
                    dismissrogressBar();
                    MessageTools.showDialogOk(ctx,
                            "保存成功！本次医疗服务数据保存在本机，请到“离线设置”-“上传医疗服务信息”中上传数据！");
                    break;
                case Constant.BAOCUN_ERROR:
                    dismissrogressBar();
                    MessageTools.showDialogOk(ctx, "对不起，保存本地失败。请重新测试！");
                    break;
                case  Constant.JIAOYANCODE:
                    dismissrogressBar();
                    if(infoList.size()==0) {
                        MessageTools.showDialogOk(ctx, "未查到"+shengfenzheng_str+"的相关信息");
                    }
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        dismissrogressBar();
      /*  if (data == null) {
            Toast.makeText(this, "获取数据失败！", Toast.LENGTH_SHORT).show();
            return;
        }*/
        switch (resultCode) {
            case RESULT_OK:
                final EcgData ecg = new EcgData(data);
                // Submit(ecg);
                // 对话框的创建器
                Builder builder = new Builder(this);
                builder.setIcon(getResources().getDrawable(R.drawable.logo_bg));
                builder.setTitle("心电测试完成");
                builder.setMessage("请选择对测试完的数据进行以下哪种操作？");
                builder.setPositiveButton("上传服务器", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!BphsConstants.isNetAvailable) {
                            Toast.makeText(getApplicationContext(),
                                    "由于没有联网不能上传，所以自动保存到本地！", Toast.LENGTH_SHORT).show();
                            Submitecg(ecg, 1);
                        } else {
                            Submitecg(ecg, 0);
                        }
                        // Toast.makeText(getApplicationContext(), "上传服务器被点击了",
                        // 0).show();
                    }
                });
                builder.setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Toast.makeText(getApplicationContext(), "取消被点击了",
                        // 0).show();
                    }
                });
                builder.setNeutralButton("保存到本地", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Submitecg(ecg, 1);
                    }
                });
                builder.setCancelable(false);
                builder.create().show();
                break;
//		case 1:
//			String cardName = data.getStringExtra("cardName");
//			String cardNumber = data.getStringExtra("cardNumber");
//				if (StringUtils.isNotBlank(cardName)
//						&& StringUtils.isNotBlank(cardNumber)) {
//					name_et.setText(cardName);
//					shengfenzheng_et.setText(cardNumber);
//					name_str = cardName;
//					shengfenzheng_str = cardNumber;
//				} else {
//					Toast.makeText(this, "读身份证信息失败", 0).show();
//				}
//			break;
            case 2:
                // 获取血压值
                String result = data.getStringExtra("jsonstr");
                JSONObject json;
                try {
                    json = new JSONObject(result);
                    String cSP = json.getString("cSP");
                    String cDP = json.getString("cDP");
                    shousuoya_et.setText(cSP);
                    shuzhangya_et.setText(cDP);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                break;
            case 3:
                // 获取血氧
                String cPulseRate = data.getStringExtra("cPulseRate");
                String cxueyang = data.getStringExtra("cxueyang");
                xueyang_et.setText(cxueyang);
                mailv_et.setText(cPulseRate);
                break;
            case 4:
                // 获取血糖

                try {
                    String jsonstr = data.getStringExtra("jsonstr");
                    JSONObject jsonr = new JSONObject(jsonstr);
                    String gGLU = jsonr.getString("gGLU");
                    xuetang_et.setText(gGLU);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                break;
            case 5:
                // 获取心电

                break;
            case 6:
                // 获取尿常规
                String msg = data.getStringExtra("msg");
                niaocg_et.setText(msg);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 请求服务器

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//		case R.id.chaxuan_btn:// 查询按钮
//			loadWaitPanel();
////			Intent intent = new Intent(this, CardActivity.class);
////			startActivityForResult(intent, 1);
//			return;
            case R.id.jiaoyanbtn://校验
                infoList.clear();
                shengfenzheng_str= shengfenzheng_et.getText().toString();
                if(TextUtils.isEmpty(shengfenzheng_str)){
                    MessageTools.showDialogOk(ctx,"请输入正确的省份证号进行校验");
                }else {
                    getPersonInfo();
                } return;
            case R.id.celiang_xueya_btn:// 血压
                Intent iNibp = new Intent(YiliaoServiceActivity.this,
                        NibpExample.class);
                startActivityForResult(iNibp, 2); // 获取血压值
                return;
            case R.id.celiang_xueyang_btn:// 血氧
                Intent iSpo2 = new Intent(YiliaoServiceActivity.this,
                        Spo2Example.class);
                startActivityForResult(iSpo2, 3); // 获取心率值
                return;
            case R.id.celiang_xuetang_btn:// 血糖
                Intent iGlu = new Intent(YiliaoServiceActivity.this,
                        GluExample.class);
                startActivityForResult(iGlu, 4); // 获取血糖值
                return;
            case R.id.celiang_xindian_btn:// 心电
			if (1!= BphsConstants.deviceBranchType) {
				MessageTools.showDialogOk(ctx, "此功能暂时只支持盖瑞设备！");
				return;
			}
                if (StringTools.isEmpty(name_et.getText().toString().trim())) {
                    MessageTools.showDialogOk(ctx, "没有测试人员！");
                    return;
                }
//			Intent intentxindian = new Intent(act, XDpersonActivity.class);
//			Bundle bundle = new Bundle();
//			bundle.putString("sPersonID", "");
//			bundle.putString("sNo", "");
//			bundle.putString("sPersonName", name_et.getText().toString().trim());
//			bundle.putString("sCardNo", shengfenzheng_et.getText().toString().trim());
//			bundle.putString("IsService", "1");
//			intentxindian.putExtras(bundle);
//			startActivity(intentxindian);
//			ComponentName componentName = new ComponentName(
//					"com.garea.measurer",
//					"com.garea.measurer.app.YLEcgExample");
                if(infoList.size()>0){
                    Intent intent = new Intent(YiliaoServiceActivity.this, YLEcgExample.class);
                    //	intent.setComponent(componentName);
                    intent.putExtra("sexName", sexName);
                    intent.putExtra("birthday", birthday);
                    this.startActivityForResult(intent, 0);
                }else{
                    MessageTools.showDialogOk(ctx,"请确认"+shengfenzheng_et.getText().toString()+"是否可以检测心电项目");
                }

                return;
            case R.id.celiang_niaochanggui_btn:// 尿常规
//			Intent intentdata = new Intent(YiliaoServiceActivity.this,
//					UriActivity.class);
//			startActivityForResult(intentdata, 6);
                return;
            case R.id.baocun_btn:
                sPersonName = name_et.getText().toString().trim();
                sCardNo = shengfenzheng_et.getText().toString().trim();
                if (StringTools.isEmpty(sCardNo)) {
                    MessageTools.showDialogOk(ctx, "没有测试人员！");
                    return;
                }
                xueyagao = shousuoya_et.getText().toString().trim();
                xueyadi = shuzhangya_et.getText().toString().trim();
                xueyang = xueyang_et.getText().toString().trim();
                mailv = mailv_et.getText().toString().trim();
                kongfuxueytang = xuetang_et.getText().toString().trim();
                niaochanggui = niaocg_et.getText().toString().trim();


                Builder builder = new Builder(this);
                builder.setIcon(getResources().getDrawable(R.drawable.logo_bg));
                builder.setTitle("测试完成");
                builder.setMessage("请选择对测试结果数据进行以下哪种操作？");
                builder.setPositiveButton("上传服务器", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!BphsConstants.isNetAvailable) {
                            Toast.makeText(getApplicationContext(), "由于没有联网不能上传，所以自动保存到本地！", Toast.LENGTH_SHORT).show();
                            Submit(1);
                        } else {
                            Submit(0);
                        }
//				Toast.makeText(getApplicationContext(), "上传服务器被点击了", 0).show();
                    }
                });
                builder.setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//				Toast.makeText(getApplicationContext(), "取消被点击了", 0).show();
                    }
                });
                builder.setNeutralButton("保存到本地", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Submit(1);
                    }
                });
                builder.setCancelable(false);
                builder.create().show();

                return;
        }
    }

    private void Submit(final int flag) {
        loadWaitPanel();
        new Thread() {
            public void run() {
                String methodName = BphsURL.getCommonPath("YiliaoService_METHOD");
                String requestUrl = BphsURL.getCommonPath("YiliaoService_URL");
                JSONObject data = new JSONObject();
//					{"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10"}
                try {
                    UserLoginInfo info = UserLoginInfo.getInstances();
                    data.put("sPersonName", sPersonName); //
                    data.put("sCardNo", sCardNo); //
                    data.put("xueyagao", xueyagao); //
                    data.put("xueyadi", xueyadi); //
                    data.put("xueyang", xueyang); //
                    data.put("mailv", mailv); //
                    data.put("kongfuxueytang", kongfuxueytang); //
                    data.put("niaochanggui", niaochanggui); //


                    data.put("sAddUser", info.getsLoginName()); //
                    data.put("sInputDeptCode", info.getsOrganizationKey()); //
                    data.put("sInputDeptName", info.getsOrganizationName()); //
                    data.put("sAreaCode", info.getsManagementDivisionCode()); //
                    data.put("dAddTime", DateTools.getFormatStringByDF_YYYY_MM_DD_HH_MM_SS(new Date())); //
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                if (flag == 0) {
                    content = WebServiceUtils.requestByParams(methodName, data.toString(), requestUrl);
                    if (StringUtils.isNotBlank(content)) {
                        try {
//							  {"sSuccess":"1","sMessage":"执行功能！","AllCount":0,"Data":"[]"}
                            Log.i(tag, "返回的查询结果" + content);
                            JSONObject json = new JSONObject(content);
                            String sResult = json.getString("sSuccess");
                            if (sResult.equals("1")) {
                                myhandler.sendEmptyMessage(Constant.TIJIAO_OVER);
                            } else {
                                myhandler.sendEmptyMessage(Constant.TIJIAO_ERROR);
                            }
                        } catch (Exception e) {
                            myhandler.sendEmptyMessage(Constant.TIJIAO_ERROR);
                            e.printStackTrace();
                        }
                    } else {
                        myhandler.sendEmptyMessage(Constant.TIJIAO_ERROR);
                    }
                } else if (flag == 1) {
                    try {

                        boolean issuccess = new FileService(act).saveToRom(
                                "",
                                "",
                                sPersonName,
                                sCardNo, "医疗服务心电"
                                ,
                                data.toString(),
                                "yiliaoservice_append.txt");

                        if (issuccess) {
                            myhandler.sendEmptyMessage(Constant.BAOCUN_OVER);
                        } else {
                            myhandler.sendEmptyMessage(Constant.BAOCUN_ERROR);
                        }
                    } catch (Exception e) {
                        myhandler.sendEmptyMessage(Constant.BAOCUN_ERROR);
                        e.printStackTrace();
                    }
                }

            }

            ;
        }.start();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDevice != null) {
            mDevice.close();
            mDevice.uninit();
        }

        if (mInspector != null) {
            mInspector.uninit();
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        // mAdapter.disableForegroundDispatch(this);

    }

    @Override
    protected void onResume() {
        super.onResume();

    }


    private byte[] getByteArrayFromShortArray(short[] shortArray) {
        if (shortArray == null) {
            return new byte[0];
        }
        BytesTransUtil bytesTransUtil = BytesTransUtil.getInstance();
        byte[] byteArray = bytesTransUtil.Shorts2BytesEcg(shortArray);
        return byteArray;
    }

    private void Submitecg(final EcgData ecg, final int flag) {
        short[] data1 = ecg.getData();
//		byte[] result = StringTools.shortArray2ByteArray(data1);
        byte[] result = getByteArrayFromShortArray(data1);
        final String str1 = Base64.encodeToString(result, Base64.NO_WRAP);

        loadWaitPanel();
        new Thread() {
            public void run() {
                String methodName = BphsURL
                        .getCommonPath("XINDIANAddToECGTB_METHOD");
                String requestUrl = BphsURL
                        .getCommonPath("XINDIANECGWebService_URL");
                JSONObject data = new JSONObject();
                // {"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10"}
                try {
                    UserLoginInfo info = UserLoginInfo.getInstances();
                    data.put("sNo", infoList.get(0).getsNo());//
                    data.put("sPersonName", sPersonName); //
                    data.put("sCardNo", sCardNo); //
                    data.put("sECGData", str1); //
                    data.put("sECGResult", ecg.getResultText()); //
                    data.put("hp", ecg.getHp()); //
                    data.put("lp", ecg.getLp()); //
                    data.put("notch", ecg.getNotch()); //
                    data.put("hr", ecg.getHr()); //
                    data.put("pAxis", ecg.getPAxis()); //
                    data.put("qrsAxis", ecg.getQrsAxis()); //
                    data.put("taxis", ecg.getTAxis()); //
                    data.put("prInterval", ecg.getPrInterval()); //
                    data.put("qrsDuration", ecg.getQrsDuration()); //
                    data.put("qtd", ecg.getQtd()); //
                    data.put("qtc", ecg.getQtc()); //
                    data.put("rv5", ecg.getRv5()); //
                    data.put("sv1", ecg.getSv1()); //
                    data.put("rv5sv1", ecg.getRv5sv1()); //
                    data.put("pWidth", ecg.getPWidth()); //
                    data.put("pExist", ecg.getPExist()); //
                    data.put(
                            "resultCodes",
                            Arrays.toString(ecg.getResultCodes())
                                    .replace("[", "").replace("]", "")); //
                    data.put("sAddUser", info.getsLoginName()); //
                    data.put("sInputDeptCode", info.getsOrganizationKey()); //
                    data.put("sInputDeptName", info.getsOrganizationName()); //
                    data.put("sAreaCode", info.getsManagementDivisionCode()); //
                    data.put(
                            "dAddTime",
                            DateTools
                                    .getFormatStringByDF_YYYY_MM_DD_HH_MM_SS(new Date())); //
                    data.put("sDoctorName", ""); //
                    data.put("sPersonID", infoList.get(0).getsPersonID()); //
                    int IsService = 1;
                    data.put("IsService", IsService); //


                    //新增字段
                    data.put("inputer", userLoginInfo.getsLoginName());//用户名
//					data.put("inputCode", ###);//用户编码
                    data.put("inputDate", DateTools.getFormatStringByDF_YYYY_MM_DD(new Date()));//录入日期
                    data.put("And_xueya", "0");//
                    data.put("And_xinlv", "1");
                    data.put("And_xuetang", "0");
                    data.put("And_xuehongdanbai", "0");
                    data.put("And_tiwen", "0");
                    data.put("And_mailv", "0");
                    data.put("And_huxipinlv", "0");
                    data.put("And_xindian", "1");
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                if (flag == 0) {
                    content = WebServiceUtils.requestByParams(methodName,
                            data.toString(), requestUrl);
                    if (StringUtils.isNotBlank(content)) {
                        try {
                            // {"sSuccess":"1","sMessage":"执行功能！","AllCount":0,"Data":"[]"}
                            Log.i(tag, "返回的查询结果" + content);
                            JSONObject json = new JSONObject(content);
                            String sResult = json.getString("sSuccess");
                            if (sResult.equals("1")) {
                                myhandler
                                        .sendEmptyMessage(Constant.TIJIAO_OVER);
                            } else {
                                myhandler
                                        .sendEmptyMessage(Constant.TIJIAO_ERROR);
                            }
                        } catch (Exception e) {
                            myhandler.sendEmptyMessage(Constant.TIJIAO_ERROR);
                            e.printStackTrace();
                        }
                    } else {
                        myhandler.sendEmptyMessage(Constant.TIJIAO_ERROR);
                    }
                } else if (flag == 1) {
                    try {

                        boolean issuccess = new FileService(act).saveToRom(
                                infoList.get(0).getsPersonID(), infoList.get(0).getsNo(), sPersonName, sCardNo,
                                "1".equals("1") ? "医疗服务心电" : "心电数据",
                                data.toString(), "xindian_append.txt");

                        if (issuccess) {
                            myhandler.sendEmptyMessage(Constant.BAOCUN_OVER);
                        } else {
                            myhandler.sendEmptyMessage(Constant.BAOCUN_ERROR);
                        }
                    } catch (Exception e) {
                        myhandler.sendEmptyMessage(Constant.BAOCUN_ERROR);
                        e.printStackTrace();
                    }
                }

            }

            ;
        }.start();

    }

    public void getPersonInfo() {
        loadWaitPanel();
        new Thread(sendable).start();
    }
    // 请求服务器
    private Runnable sendable = new Runnable() {
        public void run() {
            String methodName = "GetPersonInfoManageData";//BphsURL.getCommonPath("GetPersonInfoByECG_METHOD");
            String requestUrl = BphsURL.getCommonPath("GetPersonInfoManageData_URL");
            // String requestUrl =
            // "http://60.171.146.122:9098/WebService/Andrews/PsychosisPersonWebService.asmx";
            Log.i(tag, "查询:content" + requestUrl);
            // String methodName="GetPsychosisPersonManageData";
            JSONObject data = new JSONObject();
            // {"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10"}
            try {
                UserLoginInfo info = UserLoginInfo.getInstances();
                data.put("sAreaCode", info.getsManagementDivisionCode());//
                if (jiciNum != 0) {
                    data.put("iCurrentPageIndex", (jiciNum * 10 + 1) + "");
                } else {
                    data.put("iCurrentPageIndex", "1");
                }
                data.put("iPageSize", "10"); //
                data.put("sNo", ""); //
                data.put("sPersonName", name_str); //
                data.put("sCardNo", shengfenzheng_str); //
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            content = WebServiceUtils.requestByParams(methodName,
                    data.toString(), requestUrl);
            if (StringUtils.isNotBlank(content)) {
                try {
                    Log.i(tag, "返回的查询结果" + content);
                    // String result= content.replaceAll("\\\\", "");
                    // Log.i(tag, "返回的查询结果"+result);
                    JSONObject json = new JSONObject(content);
                    // Log.i(tag, "返回的查询结果"+result);"AllCount":0,
                    // allcount= 28;
                 //    allcount = json.getLong("AllCount");
                    JSONObject jo = new JSONObject(json.getString("Data"));
                    JSONArray jsonArray = (JSONArray) jo.get("Table");
                    for (int i = 0; i < jsonArray.length(); ++i) {
                        JSONObject o = (JSONObject) jsonArray.get(i);
                        PersonnelInformation info = new PersonnelInformation(
                                o.getString("sPersonID"), o.getString("sNo"),
                                o.getString("sPersonName"),
                                o.getString("sSexName"),
                                o.getString("dBirthday"),
                                o.getString("sCardNo"),
                                o.getString("sHouseholdTypeName"),
                                o.getString("sInputDeptName"),
                                o.getString("sAreaProvinceName")
                                        + o.getString("sAreaCityName")
                                        + o.getString("sAreaCountryName")
                                        + o.getString("sAreaTownName")
                                        + o.getString("sAreaVillageName")
                                        + o.getString("sAreaGroup"),
                                o.getString("sPhone"),
                                o.getString("IsECGTB"));

                        infoList.add(info);
                        if(infoList.size()==0){
                            myhandler.sendEmptyMessage(Constant.JIAOYANCODE);
                        }else{
                            dismissrogressBar();
                        }

                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    myhandler.sendEmptyMessage(Constant.JIAOYANCODE);
                }

            }
        }
    };
}